package filecopy;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AckThread extends Thread {

    private DatagramSocket dSocket;
    private int bufferSize;
    private Window window;
    private FileCopyClient fcc;

    public AckThread(DatagramSocket dSocket, int bufferSize, Window window, FileCopyClient fcc) {
        this.dSocket = dSocket;
        this.bufferSize = bufferSize;
        this.window = window;
        this.fcc = fcc;
    }

    public void run() {
        while (!this.isInterrupted()) {
            byte[] receiveData = new byte[bufferSize];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, bufferSize);
            try {
                dSocket.receive(receivePacket);
                //System.out.println(Arrays.toString(receiveData));
                long seqNum = FCpacket.makeLong(receiveData, 0, 8);
                
                FCpacket packet = window.getBySequenceNumber(seqNum);
                if (packet != null) {
                    long sampleRTT = System.nanoTime() - packet.getTimestamp();
                    //System.out.println("SequenceNumACK: " + seqNum + " CurrentSystemNanos" + System.nanoTime());
                    fcc.computeTimeoutValue(sampleRTT);
                }
                window.setAckTrue(seqNum);
                
            } catch (IOException ex) {
                return;
            }
        }
    }
}
